//
//  AViewController.m
//  ZhiBoYuan
//
//  Created by mac on 2018/4/12.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "AViewController.h"
#import "XiaoXIViewController.h"

#import "UINavigationController+NavLine.h"

#import "CKSlideMenu.h"
#import "ASubViewController.h"
#import "AdetailViewController.h"

#import "AACell.h"
static NSString * ident = @"AACell";

#import "FourCell.h"

static NSString *identFou = @"FourCell";

#import "ABCell.h"
static NSString * identB = @"ABCell";


#import "CViewController.h"
#import "BSDetailViewController.h"
#import "BranchCourseVC.h"
#import "WebDViewController.h"

#import "HomePageModel.h"
#import "BannerModel.h"
#import "HotLiveModel.h"
#import "MicroCourseModel.h"


@interface AViewController ()
<
UITableViewDataSource,
UITableViewDelegate
>

@property (nonatomic, strong) NSMutableArray *dataArray;
//@property (nonatomic, strong) UITableView *tableView;

@property(nonatomic,strong)AxcEmptyDataTableView *tableView;



@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong)UILabel *messagelabel;

@end

@implementation AViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self downloadHomePageDatas];
    

}


- (void)downloadHomePageDatas{
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       };
    
     __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:Host_Append(HomePageDatas) parameter:parameter sucess:^(id responseObject) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        if (responseObject) {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            NSString *resultStr =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            ZYLog(@"%@",resultStr);
            //        ZYLog(@"%@",responseObject);
            SGReceive *receive = [SGReceive receiveWithResponseObject:responseObject dataClass:[HomePageModel class]];
            
            self.dataArray = [NSMutableArray array];
            [self.dataArray addObject:receive.data];
            [self.tableView reloadData];
        }

        
    } failure:^(NSError *error) {
         [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
        
    }];
    
}





- (void)initWithViews{
    NSLog(@"自定义");
    self.navigationController.title = @"自定义";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [Helper setMoRenNav:self.navigationController];
    [Helper setNavColorFrom:self.navigationController color:ZhuTiColor];
    [self.view addSubview:self.tableView];
    
    
    //    [UrlGetData postWithUrlString:url.urlPath parameters:url.dict loadTip:nil view:nil success:^(NSDictionary *data) {
    //         NSLog(@" 数据 = %@",data);
    //    } failure:^(NSError *error) {
    //        NSLog(@"❌错误❌ %@",error);
    //    }];
    
    //    [UrlGetData postWithUrlString:@"www.baidu.com" parameters:nil success:^(NSDictionary *data) {
    //         NSLog(@" 数据 = %@",data);
    //    } failure:^(NSError *error) {
    //        NSLog(@"❌错误❌ %@",error);
    //    }];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(0, 0, 40, 40);
    [button setImage:[UIImage imageNamed:@"web__消息管理-1"] forState:(UIControlStateNormal)];
    BTN_MSG_FUNC(button, messageSender);
    
    _messagelabel = [[UILabel alloc]initWithFrame:CGRectMake(28, 8, 12, 12)];
    _messagelabel.text = [ZYUserManager userInfo].news_count;//调整位置到右上角，然后旋转45度
    _messagelabel.textColor =[UIColor whiteColor];
    [_messagelabel setTextAlignment:(NSTextAlignmentCenter)];
    _messagelabel.font = [UIFont systemFontOfSize:8];
    _messagelabel.layer.masksToBounds= YES;
    _messagelabel.layer.cornerRadius = 6;
    
    if ([_messagelabel.text isEqualToString:@"0"]) {
        _messagelabel.hidden = YES;
    }else{
        
        _messagelabel.hidden = NO;
        _messagelabel.text = [ZYUserManager userInfo].news_count;
        [_messagelabel setBackgroundColor:[UIColor redColor]];
    }
    
    [button addSubview:_messagelabel];
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    

    
}

-(void)messageSender{
    XiaoXIViewController *messageVC = [[XiaoXIViewController alloc]init];
    messageVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:messageVC animated:YES];
    
    NSLog(@"查看消息");
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (_dataArray.count == 0) {
        return 0;
    }
    return 4;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else if (section == 1){
        return 40;
    }else{
      return 50;
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString * identy = @"head";
    
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    
        
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width,40)];
        
        if (section > 1) {
            view.frame =CGRectMake(0,10, self.view.frame.size.width,40);
        }

        view.backgroundColor = [UIColor whiteColor];
        NSArray *arr = @[@"",@"合作学校",@"最近直播",@"热门课程"];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40)];
        label.text = arr[section];
        
        
        UILabel *labelMore = [[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-70, 0, 40, 40)];
        
        if (section == 1) {
          labelMore.text = @"";
        }else{
          labelMore.text = @"更多";
        }
        
        
        labelMore.textColor = hui3Color;
        
        [view addSubview:labelMore];
        
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(ScreenWidth-50, 0, 50, 40);
        
        if (section == 1) {
            [button setImage:[UIImage imageNamed:@""] forState:(UIControlStateNormal)];
        }else{
            [button setImage:[UIImage imageNamed:@"箭头-45"] forState:(UIControlStateNormal)];
        }
        
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        
        
        UIButton *buttoTop = [UIButton buttonWithType:(UIButtonTypeCustom)];
        
        buttoTop.frame = CGRectMake(ScreenWidth-80, 0, 80, 40);
        buttoTop.tag = section + 100;
         BTN_MSG_FUNC(buttoTop, sender:);
        
        
        
        [view addSubview:button];
        [view addSubview:label];
        
        [view addSubview:buttoTop];
        
        [hf addSubview:view];
        
    
    
    return hf;
    
    
}

- (void)sender:(UIButton *)button{
    
    NSLog(@"%zd",button.tag-100);
    
    switch (button.tag-100) {
        case 0:
            {
                
            }
            break;
        case 1:
        {
        }
            break;
        case 2:
        {
            self.tabBarController.selectedIndex = 2;
            
            
//            BSDetailViewController *vc =[[BSDetailViewController alloc]init];
//            vc.tabHiden = YES;

//            vc.hidesBottomBarWhenPushed =YES;
//
//            [self.navigationController pushViewController:vc animated:YES];
            
            
        }
            break;
        case 3:
        {
             self.tabBarController.selectedIndex = 2;
//            BSDetailViewController *vc =[[BSDetailViewController alloc]init];
//            vc.tabHiden = YES;

//            vc.hidesBottomBarWhenPushed =YES;
//
//            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ((section == 0||section == 1) &&self.dataArray.count) {
        return 1;
    }
    if (self.dataArray.count) {
        HomePageModel *model = self.dataArray[0];
        if (section == 2) {
            return model.recent_live_list.count;
        }else if (section == 3){
            return model.hot_live_list.count;
        }
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        AACell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
        cell.bannerList = [self.dataArray[0] banner_list];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        //    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        //    zjsDataBaseLesson *data = self.lessonArray[indexPath.row];
        //    [cell loadData:data];
        cell.clickBanner = ^(BannerModel *banner) {
            ZYLog(@"%@",banner.link_url);
            NSURL *url = [NSURL URLWithString:banner.link_url];
            ZYLog(@"\n%@\n%@\n%@",url.scheme,url.host,url.lastPathComponent);
            if (url.scheme && [url.scheme isEqualToString:@"zby"]) {
                if (url.host && [url.host isEqualToString:@"course_info"]) {
                    //                    NSString *typeStr = [host componentsSeparatedByString:@"."].firstObject
//                    AdetailViewController *vc= [[AdetailViewController alloc]initWithNibName:@"AdetailViewController" bundle:nil];
//                    vc.hidesBottomBarWhenPushed =YES;
//                    vc.course_id = url.lastPathComponent;
//                    [self.navigationController pushViewController:vc animated:YES];
                    

                    [Helper keChengDetailFromVC:self course_id:url.lastPathComponent];
                    
                    
                    
                }else if (url.host && [url.host isEqualToString:@"fenyuan"]){
                    BranchCourseVC *branch = [BranchCourseVC new];
                    branch.titleName = banner.name;
                    branch.fenyuan_id = url.lastPathComponent;
                    branch.hidesBottomBarWhenPushed =YES;
                    [self.navigationController pushViewController:branch animated:YES];
                    
                }
            }else{
                WebDViewController * webAD = [[WebDViewController alloc] init];
                webAD.urlString = banner.link_url;
                webAD.titleName = banner.name;
                webAD.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webAD animated:YES];
                
            }
            
        };
        
        return cell;

    }else if (indexPath.section == 1) {
        FourCell *cell = [tableView dequeueReusableCellWithIdentifier:identFou forIndexPath:indexPath];
        cell.adArray = [self.dataArray[0] sub_banner_list];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        
        cell.clickBanner = ^(BannerModel *banner) {
            NSURL *url = [NSURL URLWithString:banner.link_url];
            if (url.scheme && [url.scheme isEqualToString:@"zby"]) {
                if (url.host && [url.host isEqualToString:@"course_info"]) {
                    
                    [Helper keChengDetailFromVC:self course_id:url.lastPathComponent];
                    
                }else if (url.host && [url.host isEqualToString:@"fenyuan"]){
                    BranchCourseVC *branch = [BranchCourseVC new];
                    branch.fenyuan_id = url.lastPathComponent;
                    branch.hidesBottomBarWhenPushed =YES;
                    branch.titleName = banner.name;
                    [self.navigationController pushViewController:branch animated:YES];

                }
            }else{
                
                WebDViewController * webAD = [[WebDViewController alloc] init];
                webAD.urlString = banner.link_url;
                webAD.titleName = banner.name;
                webAD.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webAD animated:YES];
            }
        };
        
        
        return cell;
    }else if(indexPath.section == 2){
        ABCell *cell = [tableView dequeueReusableCellWithIdentifier:identB forIndexPath:indexPath];
        HomePageModel *model = self.dataArray[0];
        cell.microModel = model.recent_live_list[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        //    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        //    zjsDataBaseLesson *data = self.lessonArray[indexPath.row];
        //    [cell loadData:data];
        
        return cell;
    }else{
        ABCell *cell = [tableView dequeueReusableCellWithIdentifier:identB forIndexPath:indexPath];
        HomePageModel *model = self.dataArray[0];
        cell.microModel = model.hot_live_list[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        //    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        //    zjsDataBaseLesson *data = self.lessonArray[indexPath.row];
        //    [cell loadData:data];
        
        return cell;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return SNRealValue(50);
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    AdetailViewController *vc= [[AdetailViewController alloc]initWithNibName:@"AdetailViewController" bundle:nil];
//    HomePageModel *model = self.dataArray[0];
//
//    MicroCourseModel *microModel = model.hot_live_list[indexPath.row];
//
//    vc.course_id = microModel.microCourseID;

//    vc.hidesBottomBarWhenPushed =YES;
//
//    [self.navigationController pushViewController:vc animated:YES];
    
    HomePageModel *model = self.dataArray[0];
    
    if (indexPath.section == 2) {
        MicroCourseModel *microModel = model.recent_live_list[indexPath.row];
         [Helper keChengDetailFromVC:self course_id:microModel.microCourseID];
    }else{
        
        MicroCourseModel *microModel = model.hot_live_list[indexPath.row];
         [Helper keChengDetailFromVC:self course_id:microModel.microCourseID];
    }
   
}

#pragma makr -- property
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (AxcEmptyDataTableView *)tableView {
    if (!_tableView) {
      AxcEmptyDataTableView *  tableView = [[AxcEmptyDataTableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT -TAB_BAR_HEIGHT) style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
//        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        tableView.scrollIndicatorInsets = _tableView.contentInset;
        
//         [tableView registerNib:[UINib nibWithNibName:identC bundle:nil] forCellReuseIdentifier:identC];
        [tableView registerNib:[UINib nibWithNibName:identB bundle:nil] forCellReuseIdentifier:identB];
        
        [tableView registerNib:[UINib nibWithNibName:identFou bundle:nil] forCellReuseIdentifier:identFou];
        
        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            
            [weakSelf downloadHomePageDatas];

//            weakSelf.pageIndex = 1;

//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf.tableView.mj_header endRefreshing];
//            });
        }];
//
//        // 上拉加载
//        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//
//            if ( weakSelf.pageIndex < -1 ) {  weakSelf.pageIndex = 1;  }
//
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf.tableView.mj_footer endRefreshing];
//            });
//        }];
        
        self.placeholderView.frame = tableView.bounds;
        
        // 设置空集时候展示的View
        tableView.axcUI_placeHolderView = self.placeholderView;
        
        //  默认YES 自带渐入渐出动画效果，下边这个参数可以关闭
        tableView.axcUI_placeHolderViewAnimations = NO;
        
        // 占位View的“重新加载”按钮的Block回调:
        __weak typeof(self) WeakSelf = self;
        
        self.placeholderView.clickLoadBtnBlock = ^(id type) {
            //        WeakSelf.dataArray = nil;
            
            
            [WeakSelf downloadHomePageDatas];
            
        };
        
        
        _tableView = tableView;
        
    }
    return _tableView;
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [Helper setMoRenNav:self.navigationController];
    [Helper setNavColorFrom:self.navigationController color:ZhuTiColor];

    [self extracted];
     [self initWithViews];
    
}
- (void)extracted {
    [self loadUnReadMessage];
}


-(void)loadUnReadMessage{
    SGParameter *parameter  = [[SGParameter alloc] init];
    NSLog(@"%@",[ZYUserManager userInfo].unreadMessageId);
    parameter.body = @{@"max_news_id":[NSString stringWithFormat:@"%@",[ZYUserManager userInfo].unreadMessageId]
                       };

    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Ucenter&a=newsCount",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);

        if ([responseObject[@"status"] intValue] == 200) {
            UserinfoModel *model = [ZYUserManager userInfo];
            model.news_count = [responseObject[@"data"] valueForKey:@"news_count"];
            _messagelabel.text = [NSString stringWithFormat:@"%@",[responseObject[@"data"] valueForKey:@"news_count"]];
            if ([_messagelabel.text isEqualToString:@"0"]) {
                _messagelabel.hidden = YES;
            }else{

                _messagelabel.hidden = NO;
            }

            [ZYUserManager saveUserInfo:model];

        }else{
            [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0f];
        }

    } failure:^(NSError *error) {
        NSLog(@"%@",error);

    }];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    
    
}




//#pragma mark - TableView 占位图
//- (UIImage *)xy_noDataViewImage
//{
//    return [UIImage imageNamed:@"Load_failed"];
//}

//- (NSString *)xy_noDataViewMessage
//{
//    return @"没有要展示内容.....";
//}

//- (UIColor *)xy_noDataViewMessageColor
//{
//    return [UIColor blackColor];
//}

//- (void)xy_reloadDataView
//{
//    _pageIndex = 1;
//
//    [self downloadHomePageDatas];
//
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
